import {
	sub
} from '@/common/event.js'
import store from '../index.js'
import moment from 'moment'
import {
	getRqst
} from '../../common/request'

export default {
	namespaced: true,
	state: {
		list: []
	},
	mutations: {
		cleardata: (state, payload) => {
			state.list = []
		},
		setLivelist: (state, payload) => {
			const ids = []
			for(let o of payload){
				if(ids.includes(o.uid)){
					continue
				}
				ids.push(o.uid)
				state.list.push(o)
			}
			// state.list = payload
		},
		addroom: (state, payload) => {
			const ret = state.list.find(e=>e.uid == payload.uid)
			if(!ret){
				state.list.unshift(payload)
			}
			
		},
		delroom: (state, payload) => {
			state.list = state.list.filter(e => e.uid != payload.id)
		},
		infochange: (state, payload) => {
			for (let o of state.list) {
				if (o.uid == payload.uid) {
					for (let k in payload) {
						o[k] = payload[k]
					}
					break
				}
			}
		}
	},
	actions: {
		async init({
			commit,
			state
		}, {
			payload
		}) {
			const ret = await getRqst().get(`friend/friend/getliveroomlist`)
			if (ret && ret.success && ret.data && ret.data.length > 0) {
				commit(`setLivelist`, ret.data)
			}
		},
	},
	init: async function() {
		console.log("liveroom初始化")

		const user = uni.getStorageSync("user")
		if (user && user.id) {
			store.dispatch({
				type: "liveroom/init",
				payload: {}
			})
		}

		sub("loginSuccess", () => {
			store.dispatch({
				type: "liveroom/init",
				payload: {}
			})
		})
		
		sub("logout", function(e) {
			store.commit(`liveroom/cleardata`, {})
		})

		sub("socket_liveroomstart", (e) => {
			store.commit("liveroom/addroom", e)
		})

		sub("socket_liveroomstop", (e) => {
			store.commit("liveroom/delroom", e)
		})

		sub("socket_liveroomchange", (e) => {
			store.commit("liveroom/infochange", e)
		})
		
		sub("socket_liveroomdistroy", (e) => {
			store.commit("liveroom/delroom", {id:e})
		})
		
		sub("relink", () => {
			store.dispatch({
				type: "liveroom/init",
				payload: {}
			})
		})

	}
}